#!/usr/bin/env python
# coding: utf-8
import web
from config import settings
from config import util
import datetime,json
import authbase

render = settings.render
db = settings.db

class HourGroupDayChart(authbase.AuthBase):
    def GET(self):
        stations_input = web.input(stations=[])
        #print "stations_input:%s"%stations_input
        stations = stations_input.get('stations',None)
        where_str=" 1=1 "
        if stations:
            where_str=where_str+" and site in ('"+"','".join(stations)+"')"
            selected_stations=stations
        else:
            selected_stations=[]

        date_list_input = web.input(date_list=[])
        date_list = date_list_input.get('date_list', None)
        #如果没有日期，则显示本月1号
        if date_list is None or len(date_list)==0:
            first_day=datetime.date.today().replace(day=1)
            date_list=[first_day.strftime("%Y-%m-%d")]
        where_str=where_str+" and collection_date in ('"+"','".join(date_list)+"')"
        selected_date_list=date_list

        i = web.input()
        #显示自动计算平均值和最大最小值
        reference_compute_avg=i.get('reference_compute_avg', False)
        #根据监测站、日期、数据类型来查询，显示月均值，水平线
        reference_month_avg=i.get('reference_month_avg', False)
        #根据监测站、日期、数据类型来查询，显示日均值，水平线
        reference_day_avg=i.get('reference_day_avg', False)
        #根据监测站、日期、数据类型来查询，显示每时段月均值，折线
        reference_month_avg_group_hour=i.get('reference_month_avg_group_hour', False)

        start_hour = i.get('start_hour', None)
        if start_hour is None:
            start_hour="00"
        where_str=where_str+" and collection_hour >= '"+start_hour+"'"
        selected_start_hour=start_hour

        end_hour = i.get('end_hour', None)
        if end_hour is None:
            end_hour="23"
        where_str=where_str+" and collection_hour <= '"+end_hour+"'"
        selected_end_hour=end_hour

        data_type_input = web.input(data_type=[])
        #print "data_type_input:%s"%data_type_input
        data_type_names = data_type_input.get('data_type',None)
        #必须是按监测站、年月、时段排序
        #将查询结果转为list，可以多次遍历
        data_list =list(db.query("SELECT * FROM v_site_hour_day_group_data  where "+where_str +" order by site,collection_date,collection_hour"))
        stations=list(db.select('stations'))
        line_name_dict,chart_data_dict,month_avg_dict,day_avg_dict=self.create_chart_data(selected_stations,selected_date_list,selected_start_hour,\
                                                              selected_end_hour,data_type_names,data_list,reference_month_avg,\
                                                              reference_day_avg,reference_month_avg_group_hour)
        return render.hour_charts.hour_group_day_chart(data_list=data_list,chart_data_json=json.dumps(chart_data_dict,ensure_ascii=False), line_name_dict=line_name_dict,stations=stations,\
                                      selected_stations=selected_stations,selected_date_list=selected_date_list,data_type_names=data_type_names,\
                                      data_type_titles=util.create_field_title_by_avg_name(data_type_names),selected_start_hour=selected_start_hour,selected_end_hour=selected_end_hour,\
                                      reference_compute_avg=reference_compute_avg,reference_month_avg=reference_month_avg,reference_day_avg=reference_day_avg,\
                                      reference_month_avg_group_hour=reference_month_avg_group_hour,\
                                      month_avg_dict=month_avg_dict,day_avg_dict=day_avg_dict)

    def create_chart_data(self,selected_stations,selected_date_list,selected_start_hour,selected_end_hour,data_type_names,\
                          data_list,reference_month_avg,reference_day_avg,reference_month_avg_group_hour):
        #按监测站、年月、参数类型的组合方式来生成曲线
        data_dict={}
        line_dict={}
        month_avg_dict={}#月均值字典，key为line的名称，value为 数值;markline的名称
        day_avg_dict={}#日均值字典，key为line的名称，value为 数值;markline的名称
        reference_lines_array=[]#存放每时段月均值曲线名称的数组，防止选择同一个月份时重复添加
        i=0
        if selected_stations is None:
            return line_dict,data_dict
        for station in selected_stations:
            short_name=station[0:2]
            for selected_date in selected_date_list:
                for data_type in data_type_names:
                    title=short_name+"("+selected_date+")"+util.data_type_title_dict[data_type]
                    #生成数据
                    row_array=[]
                    for data in data_list:
                        if data.site==station and data.collection_date==selected_date and data.collection_hour>=selected_start_hour and data.collection_hour<=selected_end_hour:
                            row_array.append(str(data[data_type]))
                    if len(row_array)==0:
                        continue
                    #曲线编号和中文名称对应
                    line_dict[data_type+"_%02d"%i]=title
                    data_dict[data_type+"_%02d"%i]=row_array
                    #根据监测站、日期、数据类型来查询，显示月均值，水平线
                    if reference_month_avg:
                        month_avg_title=short_name+util.data_type_title_dict[data_type]+u"月均值("+selected_date[0:7]+")"
                        month_avg_value=self.query_month_avg_value(station,data_type,selected_date[0:7])
                        if month_avg_value:
                            month_avg_dict[data_type+"_%02d"%i]=month_avg_value+";"+month_avg_title
                    else:
                        pass
                    #根据监测站、日期、数据类型来查询，显示日均值，水平线
                    if reference_day_avg:
                        day_avg_title=short_name+util.data_type_title_dict[data_type]+u"日均值("+selected_date+")"
                        day_avg_value=self.query_day_avg_value(station,data_type,selected_date)
                        if day_avg_value:
                            day_avg_dict[data_type+"_%02d"%i]=day_avg_value+";"+day_avg_title
                    else:
                        pass
                    #根据监测站、日期、数据类型来查询，显示每时段月均值，折线
                    if reference_month_avg_group_hour:
                        month_avg_hour_title=short_name+util.data_type_title_dict[data_type]+u"每时段月均值("+selected_date[0:7]+")"
                        if month_avg_hour_title in reference_lines_array:
                            print "month_avg_hour_title:%s is exits"%month_avg_hour_title
                        else:
                            month_avg_hour_array=self.query_month_avg_hour_array(station,data_type,selected_date[0:7],selected_start_hour,selected_end_hour)
                            if month_avg_hour_array:
                                reference_lines_array.append(month_avg_hour_title)
                                line_dict[data_type+"_%02d_month_avg_hour"%i]=month_avg_hour_title
                                data_dict[data_type+"_%02d_month_avg_hour"%i]=month_avg_hour_array
                            else:
                                print "month_avg_hour_array is None"
                    else:
                        print "not select reference_month_avg_group_hour"
                    i=i+1
        #print data_dict
        return line_dict,data_dict,month_avg_dict,day_avg_dict

    def query_month_avg_value(self,station_name,data_type,selected_month):
        sql="select "+data_type+" as data from v_site_month_data where site='"+station_name+"' and collection_month='"+selected_month+"' limit 1"
        results = db.query(sql)
        if results:
            return str(results[0].data)
        else:
            return False
    def query_day_avg_value(self,station_name,data_type,selected_date):
        sql="select "+data_type+" as data from v_site_day_data where site='"+station_name+"' and collection_date='"+selected_date+"' limit 1"
        results = db.query(sql)
        if results:
            return str(results[0].data)
        else:
            return False
    #查询某个环境指标在某个月的每时段均值
    def query_month_avg_hour_array(self,station_name,data_type,selected_month,selected_start_hour,selected_end_hour):
        sql="select "+data_type+" as data from v_site_hour_month_group_data where site='"+station_name+"' and collection_month='"+selected_month\
            +"' and collection_hour>='"+selected_start_hour+"' and collection_hour<='"+selected_end_hour+"' order by collection_hour"
        results = db.query(sql)
        if results:
            result_array=[]
            for item in results:
                result_array.append(str(item.data))
            #print result_array
            return result_array
        else:
            return False
#------------------------------------------------------------------------------------------------------------
class HourGroupMonthChart(authbase.AuthBase):
    def GET(self):
        stations_input = web.input(stations=[])
        #print "stations_input:%s"%stations_input
        stations = stations_input.get('stations',None)
        where_str=" 1=1 "
        if stations:
            where_str=where_str+" and site in ('"+"','".join(stations)+"')"
            selected_stations=stations
        else:
            selected_stations=[]


        date_list_input = web.input(date_list=[])
        date_list = date_list_input.get('date_list', None)
        #默认
        if date_list:
            where_str=where_str+" and collection_month in ('"+"','".join(date_list)+"')"
            selected_date_list=date_list
        else:
            selected_date_list=[]

        i = web.input()
        #显示自动计算平均值和最大最小值
        reference_compute_avg=i.get('reference_compute_avg', False)

        start_hour = i.get('start_hour', None)
        if start_hour is None:
            start_hour="00"
        where_str=where_str+" and collection_hour >= '"+start_hour+"'"
        selected_start_hour=start_hour

        end_hour = i.get('end_hour', None)
        if end_hour is None:
            end_hour="23"
        where_str=where_str+" and collection_hour <= '"+end_hour+"'"
        selected_end_hour=end_hour

        data_type_input = web.input(data_type=[])
        #print "data_type_input:%s"%data_type_input
        data_type_names = data_type_input.get('data_type',None)
        #必须是按监测站、年月、时段排序
        #将查询结果转为list，可以多次遍历
        data_list =list(db.query("SELECT * FROM v_site_hour_month_group_data  where "+where_str +" order by site,collection_month,collection_hour"))
        stations=list(db.select('stations'))
        line_name_dict,chart_data_dict=self.create_chart_data(selected_stations,selected_date_list,selected_start_hour,selected_end_hour,data_type_names,data_list)
        return render.hour_charts.hour_group_month_chart(data_list=data_list,chart_data_json=json.dumps(chart_data_dict,ensure_ascii=False), line_name_dict=line_name_dict,stations=stations,\
                                      selected_stations=selected_stations,selected_date_list=selected_date_list,data_type_names=data_type_names,\
                                      data_type_titles=util.create_field_title_by_avg_name(data_type_names),selected_start_hour=selected_start_hour,selected_end_hour=selected_end_hour,\
                                      reference_compute_avg=reference_compute_avg)

    def create_chart_data(self,selected_stations,selected_date_list,selected_start_hour,selected_end_hour,data_type_names,data_list):
        #按监测站、年月、参数类型的组合方式来生成曲线
        data_dict={}
        line_dict={}
        i=0
        if selected_stations is None:
            return line_dict,data_dict
        for station in selected_stations:
            short_name=station[0:2]
            for selected_date in selected_date_list:
                for data_type in data_type_names:
                    title=short_name+"("+selected_date+")"+util.data_type_title_dict[data_type]
                    #生成数据
                    row_array=[]
                    for data in data_list:
                        if data.site==station and data.collection_month==selected_date and data.collection_hour>=selected_start_hour and data.collection_hour<=selected_end_hour:
                            row_array.append(str(data[data_type]))
                    if len(row_array)==0:
                        continue
                    #曲线编号和中文名称对应
                    line_dict[data_type+"_%02d"%i]=title
                    data_dict[data_type+"_%02d"%i]=row_array
                    i=i+1
        #print data_dict
        return line_dict,data_dict
